package cn.edu.nit.sys.handle;

import cn.edu.nit.sys.utils.JwtUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.apache.catalina.connector.Response;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WebInterceptorHandler implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(ObjectUtils.isEmpty(token)) {
            response.setStatus(Response.SC_FORBIDDEN);
            response.getWriter().println("请先登陆");
            return false;
        }
        if(ObjectUtils.isEmpty(JwtUtils.getInfoFromToken(request)) || JwtUtils.isExpire(JwtUtils.parseToken(token))) {
            response.setStatus(Response.SC_UNAUTHORIZED);
            response.getWriter().println("身份已过期");
            return false;
        }
        if(!JwtUtils.getInfoFromToken(request).get("username").equals(request.getHeader("name"))) {
            response.setStatus(Response.SC_METHOD_NOT_ALLOWED);
            response.getWriter().println("非法用户");
        }
        return true;
    }
}
